package com.jwgf.common;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class IPConfig {
    private static String fileName = "IP";
    private static SharedPreferences sp = AppContext.getInstance().getSharedPreferences(fileName, Context.MODE_PRIVATE);


    // 启动can以后这个函数无效，检测到ETH连接
    public static boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) AppContext.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }

        return false;
    }

    public static boolean ping() {

        String result = null;
        try {
            String ip = getServerIp();// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }

    public static String getIp() {
        String ip;
        if (Build.VERSION.RELEASE.equals("6.0.1")) {
            ip = Settings.System.getString(AppContext.getInstance().getContentResolver(), "ethernet_static_ip");

        } else {
            ip = getWifiIp();
        }

        return ip;
    }

    public static String getWifiIp() {
        WifiManager wifiManager = (WifiManager) AppContext.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            String ip = intToIp(ipAddress);
            return ip;
        } else {
            return getIpAddressString();
        }

    }

    public static String getWifiMAC() {
        WifiManager wifiManager = (WifiManager) AppContext.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String mac = wifiInfo.getMacAddress();
            mac = mac.toUpperCase();
            return mac;
        }
        return null;

    }

    public static String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    public static String getIpAddressString() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                    .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        if (netI.getDisplayName().equals("eth0")) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void setIp(String ip) {
        Settings.System.putString(AppContext.getInstance().getContentResolver(), "ethernet_static_ip", ip);
    }

    public static String getServerIp() {
        return sp.getString("serverIp", "192.168.2.217");
    }

    public static void setServerIp(final String ip) {
        sp.edit().putString("serverIp", ip).commit();
    }

    public static String getPort() {
        return sp.getString("serverPort", "1883");
    }

    public static void setPort(String port) {
        sp.edit().putString("serverPort", port).commit();
    }

    public static String getServerURI() {
        return "tcp://" + getServerIp() + ":" + getPort();
    }

    public static String getMachineID() {
        return sp.getString("machineID", "ydh9001");
    }

    public static void setMachineID(String id) {
        sp.edit().putString("machineID", id).commit();
    }

}
